package com.jy.wms.service;

import PTLwebService.Inventory;
import PTLwebService.Result;
import PTLwebService.Service1;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.*;
import com.jy.wms.dao.*;
import com.jy.wms.pojo.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName: WmsOrderRepairService.java
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author LH
 * @Date Mon Nov 13 09:20:56 GMT+08:00 2017
 */

@Service
public class WmsOrderRepairService extends BaseService<WmsOrderRepairMapper, WmsOrderRepair> {

    @Autowired
    private WmsOwnerMapper wmsOwnerMapper;
    @Autowired
    private WmsStockMapper wmsStockMapper;
    @Autowired
    private WmsGoodsMapper wmsGoodsMapper;
    @Autowired
    private WmsOrderRepairDetailedMapper wmsOrderRepairDetailedMapper;
    @Autowired
    private WmsOrderRepairMiddelMapper wmsOrderRepairMiddelMapper;
    @Autowired
    private WmsArtificialReplenishmentMapper wmsArtificialReplenishmentMapper;
    @Autowired
    private WmsPdaReplenishmentMapper wmsPdaReplenishmentMapper;
    @Autowired
    private WmsReplenishmentLogService wmsReplenishmentLogService;
    @Autowired
    private WmsReplenishmentLogMapper wmsReplenishmentLogMapper;
    @Autowired
    WmsPdaMsgMapper wmsPdaMsgMapper;


    /**
     * 分页查询
     *
     * @param entity 实体
     * @return Page<WmsOrderRepair>
     */

    @BaseServiceDescribe(moduleName = "订单驱动补货", btnName = "查询驱动补货订单")
    public Page<WmsOrderRepair> baseSelectPage(WmsOrderRepair entity, String ckid) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          Calendar c = Calendar.getInstance();
        if (entity.getCjsj_start() != null && entity.getCjsj_start() != "") {
            c.setTime(new Date(Long.valueOf(entity.getCjsj_start())));
            c.set(Calendar.HOUR_OF_DAY, 00);
            c.set(Calendar.MINUTE, 00);
            c.set(Calendar.SECOND, 00);
            entity.setCjsj_start(df.format(c.getTime()));
        }
        if (entity.getCjsj_end() != null && entity.getCjsj_end() != "") {
            c.setTime(new Date(Long.valueOf(entity.getCjsj_end())));
            c.set(Calendar.HOUR_OF_DAY, 23);
            c.set(Calendar.MINUTE, 59);
            c.set(Calendar.SECOND, 59);
            entity.setCjsj_end(df.format(c.getTime()));
        }


        PageHelper.startPage(entity.getPage(), entity.getRows());
        return (Page<WmsOrderRepair>) dao.baseSelectPage(entity, ckid);
    }


    /**
     * 分页查询
     *
     * @param entity 实体
     * @return Page<WmsOrderRepair>
     */

    @BaseServiceDescribe(moduleName = "订单驱动补货", btnName = "查询发运订单")
    public Page<WmsShipmentOrder> getShipmentOrder(WmsShipmentOrder entity, String ckid, String hzid) {
        WmsOwner wmsOwner = wmsOwnerMapper.selectById(hzid);
        List<WmsShipmentOrder> list = new Page<WmsShipmentOrder>();
        PageHelper.startPage(entity.getPage(), entity.getRows());
        //货主配置的是否补货（1，补货）
        if (wmsOwner.getSfbh().equals(CommonInfo.owner_bh.getType())) {
            list = dao.getShipmentOrder(entity, ckid, hzid);
        }
        return (Page<WmsShipmentOrder>) list;
    }

    /**
     * 生成补货单
     * idList 发运订单id 集合
     *
     * @return
     */

    @BaseServiceDescribe(moduleName = "订单驱动补货", btnName = "生成补货单")
    @Transactional
    public void save(List<String> idList, String hzid, String ckid, String cjry) throws SucessException, ServiceException {
        //拆单明细（将拆单明细按货品ID、包装类型进行合并,数量累加。合并完成后按包装类型进行排序,按包装类型进行排序：箱>内包装>主单位
        List<WmsSplit> splitList = dao.getSplit(idList);
        List<WmsSplit> list = new ArrayList<WmsSplit>();
        WmsOrderRepair wmsOrderRepair = new WmsOrderRepair();
        wmsOrderRepair.setId(UUIDUtils.uuid());
        WmsOrderRepairDetailed wmsOrderRepairDetailed = new WmsOrderRepairDetailed();
        WmsOrderRepairMiddel wmsOrderRepairMiddel = new WmsOrderRepairMiddel();
        //如相同货品的包装类型的拣货位相同,之前已经进行过补货，后面其他相同库位跳过   而且只留下库位类型为（件拣货位、箱拣货位、箱/件拣货位）的拆单明细
        //只留下库位类型为（件拣货位、箱拣货位、箱/件拣货位）的拆单明细
        quchong(splitList);
        //如相同货品的包装类型的拣货位相同,之前已经进行过补货，后面其他相同库位跳过(去重)
        removeDuplicate(splitList);
        Integer a = 0;
        StringBuffer sb = new StringBuffer();
        Integer b=0;
        if (splitList.size() > 0) {
            for (WmsSplit ws : splitList) {
                //查询包装类型对应的表格
                String table = getTable(ws);
                //获取库位类型（0 存储库位 1件拣货库位 2箱拣货库位 3箱/件拣货库位 4待检库位 5理货库位 6组装工作库位）
                //判断货品对应的库位类型，只留下库位类型为（件拣货位、箱拣货位、箱/件拣货位）的拆单明细
                WmsOneLevelPickingLocation wmsOneLevelPickingLocation = dao.getKwlx(table, ws.getHpid());
                if (wmsOneLevelPickingLocation.getKwlx().equals(CommonInfo.jjhw.getType()) || wmsOneLevelPickingLocation.getKwlx().equals(CommonInfo.xjhw.getType()) || wmsOneLevelPickingLocation.getKwlx().equals(CommonInfo.xjjhw.getType())) {
                    //获取拣货位的库存
                    WmsStock wmsStock = dao.getWmsStock(wmsOneLevelPickingLocation.getKwid(), ws.getHpid());
                    //根据拆单明细中的货品找寻货品对应的最大补货上限和补货单位
                    WmsGoods wg = dao.getGoods(ws.getHpid());
                    String gzList = dao.getGzzd(hzid);//根据周转规则中间表获取排序字段
                    List<WmsStock> KyStockList = dao.getKyStock(gzList, ws.getHpid());//获取可用库存(存储库位)
                    //判断该货品对应的拣货位上库存是否满足拆单明细中的数量
                    //库存满足跳过此条拆单明细，判断下一个拆单明细是否可以满足(库存数量大于拆单明细的数量)

                    Double sl = 0.0;
                    if (wmsStock != null) {
                        sl = Double.parseDouble(wmsStock.getSl())- Double.parseDouble(wmsStock.getDxjsl())- Double.parseDouble(wmsStock.getDzysl())- Double.parseDouble(wmsStock.getDjsl())- Double.parseDouble(wmsStock.getPssl())- Double.parseDouble(wmsStock.getBhsl()); //拣货位的数量
                    }

                    if (sl >= Double.parseDouble(ws.getSl())) {
                        continue;
                    } else {
                        //获取补货数量
                        Double bhsl = getBhsl(wg, ws, sl);
                        NumberFormat f = new DecimalFormat("00000");
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                        if (KyStockList.size() > 0) {
                            //Integer b=0;
                            for (WmsStock wStock : KyStockList) {
                                //可用库存
                                Double kykc = Double.parseDouble(wStock.getSl()) - Double.parseDouble(wStock.getDxjsl()) - Double.parseDouble(wStock.getDzysl()) - Double.parseDouble(wStock.getDjsl()) - Double.parseDouble(wStock.getPssl()) - Double.parseDouble(wStock.getBhsl());
                                //如果可用库存小于0则跳入下一条库存
                                if (kykc <= 0) {
                                    continue;
                                } else {
                                    if (bhsl > kykc) {
                                        // 找到库存后锁定库存ID，在原有的待补货数量增加此次找寻的库存数量（存储区）。
                                        Integer count = dao.updateBhsl(wStock.getId(), String.valueOf((new BigDecimal(wStock.getBhsl()).add(new BigDecimal(kykc))).intValue()));
                                        //保存库存历史记录
                                        DigestUtil.addStockHistory(wStock.getId(),cjry,0,0,0,0,0,kykc.intValue(),2,"生成补货单");

                                        wmsOrderRepairDetailed.setBhsl(new BigDecimal(kykc));//补货数量
                                        bhsl = bhsl - kykc;
                                    } else if (bhsl <= kykc && bhsl > 0) {
                                        Integer count = dao.updateBhsl(wStock.getId(), String.valueOf((new BigDecimal(wStock.getBhsl()).add(new BigDecimal(bhsl))).intValue()));
                                        //保存库存历史记录
                                        DigestUtil.addStockHistory(wStock.getId(),cjry,0,0,0,0,0,bhsl.intValue(),2,"生成补货单");

                                        wmsOrderRepairDetailed.setBhsl(new BigDecimal(bhsl));//补货数量
                                        bhsl = bhsl - kykc;
                                    } else if (bhsl <= 0) {
                                        break;
                                    }
                                    wmsOrderRepairDetailed.setJhkcid(wmsOneLevelPickingLocation.getKwid());
                                    //将信息写入订单驱动补货主表、订单驱动补货明细表、订单驱动补货中间表

                                    //增加补货单明细 和 订单驱动补货中间表
                                     saveOrderDetailed(wmsOrderRepairDetailed, wmsOrderRepair, wg, wStock, wmsOrderRepairMiddel, idList, kykc);
                                     b++;
                                }
                            }

                        } else {
                            sb.append(ws.getHpmc()+ "没有合适的可用库存");
                        }
                    }
                }
            }
            if(b>0){
                //保存补货单主表
                a = saveOrder(wmsOrderRepair, cjry, ckid, hzid);
                a++;
            }
        } else {
            throw new ServiceException("没有合适的拆单明细");
        }
        if (a > 0) {
            if (!sb.toString().equals("")) {
                throw new SucessException("补货单生成成功,但" + sb);
            } else {
                throw new SucessException("补货单生成成功");
            }

        } else {
            if (!sb.toString().equals("")) {
                throw new ServiceException("未生成补货单，" + sb);
            } else {
                throw new ServiceException("未生成补货单，请查看是否有可用库存或者此拣货位货品是否需要补货");
            }


        }
    }

    /**
     * 只留下库位类型为（件拣货位、箱拣货位、箱/件拣货位）的拆单明细
     *
     * @param splitList 拆单明细
     */
    private void quchong(List<WmsSplit> splitList) {
        for (int i = 0; i < splitList.size(); i++) {
            String table = getTable(splitList.get(i));
            WmsOneLevelPickingLocation wmsOneLevelPickingLocation = dao.getKwlx(table, splitList.get(i).getHpid());
            if (wmsOneLevelPickingLocation.getKwlx().equals("0")) {
                splitList.remove(splitList.get(i));
                i--;
                continue;
            }
        }
    }

    /**
     * 拆单明细去重
     *
     * @param splitList 拆单明细集合
     */
    public void removeDuplicate(List<WmsSplit> splitList) {
        for (int i = 0; i < splitList.size() - 1; i++) {
            String table = getTable(splitList.get(i));
            WmsOneLevelPickingLocation wmsOneLevelPickingLocation = dao.getKwlx(table, splitList.get(i).getHpid());
            for (int j = i + 1; j < splitList.size(); j++) {
                if (splitList.get(i).getHpid().equals(splitList.get(j).getHpid())) {
                    String table2 = getTable(splitList.get(j));
                    WmsOneLevelPickingLocation wmsOneLevelPickingLocation2 = dao.getKwlx(table2, splitList.get(j).getHpid());
                    if (wmsOneLevelPickingLocation.getKwid().equals(wmsOneLevelPickingLocation2.getKwid()) || wmsOneLevelPickingLocation2.getKwlx().equals("0")) {
                        splitList.remove(splitList.get(j));
                        j--;
                    }
                }
            }
        }
    }

    /**
     * 获取补货数量
     *
     * @param wg 货品
     * @param ws 拆单明细
     * @param sl 拣货区数量
     * @return 补货数量
     */
    public Double getBhsl(WmsGoods wg, WmsSplit ws, Double sl) {

        Double bhsl = null;
        if (wg.getBhdw().equals(CommonInfo.bhdw1.getType())) {//补货单位为 箱单位
            if (wg.getQzfs().equals("2")) {//向下取整
                bhsl = Math.floor((Double.parseDouble(wg.getBhsx()) - sl) / Double.parseDouble(wg.getZdwsl())) * Double.parseDouble(wg.getZdwsl());
            } else if (wg.getQzfs().equals("1")) {//向上取整
                bhsl = Math.ceil((Double.parseDouble(wg.getBhsx()) - sl) / Double.parseDouble(wg.getZdwsl())) * Double.parseDouble(wg.getZdwsl());
            }
        } else {
            if (Double.parseDouble(ws.getSl()) > Double.parseDouble(wg.getBhsx())) {//如果拆单明细数量大于补货上限，那么补货数量为补货上限
                bhsl = Double.parseDouble(wg.getBhsx());
            } else {//如果补货数量小于补货上限，那么补货数量就按实际的补货数量补货计算，缺多少补多少
                bhsl = Double.parseDouble(ws.getSl()) - sl;
            }
        }
        return bhsl;
    }

    /**
     * 查询包装类型对应的表格
     *
     * @param ws 拆单明细
     * @return
     */
    public String getTable(WmsSplit ws) {
        String table = "";
        if (ws.getBzlx().equals(CommonInfo.bzlx0.getType())) {//主单位
            table = "wms_one_level_picking_location";
        } else if (ws.getBzlx().equals(CommonInfo.bzlx1.getType())) {//内包装
            table = "wms_two_level_picking_location";
        } else if (ws.getBzlx().equals(CommonInfo.bzlx2.getType())) {//箱
            table = "wms_three_level_picking_location";
        }
        return table;
    }

    /**
     * 获取补货编号
     *
     * @param flag 1、订单驱动补货 2、人工驱动补货
     * @return 补货编号
     */
    public String getBhbh(String flag) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        NumberFormat f = new DecimalFormat("00000");
        String a = null;
        if (flag.equals("1")) {
            a = dao.getCountByBhbh(sdf.format(new Date()));//查询当天的补货编号后5位，如果有递增，否则从00001开始
        } else if (flag.equals("2")) {
            a = wmsArtificialReplenishmentMapper.getCountByBh(sdf.format(new Date()));
        }

        String bhbh;
        if (a == null || "".equals(a)) {
            Integer i = 1;
            bhbh = sdf.format(new Date()) + f.format(i);//补货编号的生成格式（yyyyMMdd—00000(后5位数字自增)）
        } else {
            Integer b = Integer.parseInt(a);
            b++;
            bhbh = sdf.format(new Date()) + f.format(b);//补货编号的生成格式（yyyyMMdd—00000(后5位数字自增)）
        }
        return bhbh;
    }

    /**
     * 订单驱动补货主表
     *
     * @param wmsOrderRepair
     * @param cjry
     * @param ckid
     * @param hzid
     * @return
     */
    public Integer saveOrder(WmsOrderRepair wmsOrderRepair, String cjry, String ckid, String hzid) {
        String bhbh = getBhbh("1");//获取补货编号
        wmsOrderRepair.setBhbh(bhbh);
       // wmsOrderRepair.setId(UUIDUtils.uuid());
        wmsOrderRepair.setCjry(cjry);
        wmsOrderRepair.setCkid(ckid);
        wmsOrderRepair.setHzid(hzid);
        Integer a = dao.baseInsertSelective(wmsOrderRepair);
        return a;
    }


    /**
     * 订单驱动补货明细表 和 订单驱动补货中间表
     *
     * @param wmsOrderRepairDetailed
     * @param wmsOrderRepair
     * @param wg
     * @param wStock
     * @param kykc
     * @return
     */
    public Integer saveOrderDetailed(WmsOrderRepairDetailed wmsOrderRepairDetailed, WmsOrderRepair wmsOrderRepair, WmsGoods wg, WmsStock wStock, WmsOrderRepairMiddel wmsOrderRepairMiddel, List<String> idList, Double kykc) {
        wmsOrderRepairDetailed.setId(UUIDUtils.uuid());
        wmsOrderRepairDetailed.setDbhid(wmsOrderRepair.getId());
        wmsOrderRepairDetailed.setHpid(wg.getId());
        wmsOrderRepairDetailed.setKcid(wStock.getId());
        wmsOrderRepairDetailed.setYkcsl(new BigDecimal(wStock.getSl()));
        //wmsOrderRepairDetailed.setBhsl(new BigDecimal(kykc));//补货数量
        wmsOrderRepairMiddel.setDbhid(wmsOrderRepair.getId());

        for (String fydid : idList) {
            wmsOrderRepairMiddel.setId(UUIDUtils.uuid());
            wmsOrderRepairMiddel.setFyid(fydid);
            Integer b = wmsOrderRepairMiddelMapper.baseInsertSelective(wmsOrderRepairMiddel);//增加补货单与发运单明细表
        }
        Integer a = wmsOrderRepairDetailedMapper.baseInsertSelective(wmsOrderRepairDetailed);//增加补货单明细
        return a;
    }


    /**
     * 订单驱动补货中间表
     *
     * @param wmsOrderRepairMiddel
     * @param wmsOrderRepair
     * @return
     */
    public Integer saveOrderMiddle(WmsOrderRepairMiddel wmsOrderRepairMiddel, WmsOrderRepair wmsOrderRepair) {
        wmsOrderRepairMiddel.setId(UUIDUtils.uuid());
        wmsOrderRepairMiddel.setDbhid(wmsOrderRepair.getId());
        //wmsOrderRepairMiddel.setFyid();
        Integer a = wmsOrderRepairMiddelMapper.baseInsertSelective(wmsOrderRepairMiddel);//增加补货单与发运单明细表
        return a;
    }


    @BaseServiceDescribe(moduleName = "补货单", btnName = "删除补货单")
    @Transactional
    public Integer deleteOrder(List<String> idList, String scry) throws SucessException, ServiceException {
        //(1)	补货单生成状态为“已生成”不可删除   (2)	补货单状态为“已确认”不可删除

        //获取选中id的集合
        //  List<WmsOrderRepair> list = dao.selectBatchIds(idList);
        WmsStock wmsStock = new WmsStock();
        if (idList.size() > 0) {
            //删除后将补货单状态改为“作废”，填写删除人，删除时间
            Integer b = dao.deleteOrder(idList, scry);
            //删除后根据订单驱动补货明细表找寻到库存ID将库存的待补货数量减去补货数量(扣减待补货数量时要注意，当结果小于零时操作中止并抛出异常。)
            // 获取选中补货单的明细
            List<WmsOrderRepairDetailed> detailedList = wmsOrderRepairDetailedMapper.selectList(new EntityWrapper<WmsOrderRepairDetailed>().in("dbhid", idList));
            for (WmsOrderRepairDetailed word : detailedList) {
                WmsStock ws = wmsStockMapper.selectById(word.getKcid());//通过库存id获取库存对象
                BigDecimal bhsl = new BigDecimal(ws.getBhsl()).subtract(word.getBhsl());
                int a = bhsl.compareTo(BigDecimal.ZERO);
                //当结果小于零时操作中止并抛出异常
                if (a == -1) {
                    throw new ServiceException("待补货数量小于0，删除失败");
                } else {
                    ws.setBhsl(String.valueOf(bhsl.intValue()));//原待补货数量减去补货数量
                    //保存库存历史记录
                    DigestUtil.addStockHistory(word.getKcid(),scry,0,0,0,0,0,bhsl.intValue(),2,"删除补货单");

                    wmsStockMapper.updateById(ws);
                }
            }
            if (b > 0) {
                throw new SucessException("选中" + idList.size() + "条记录，删除成功" + b + "条记录");
            } else {
                throw new ServiceException("补货单删除失败");
            }
        } else {
            throw new ServiceException("选中的记录已生成或已确认，不可以删除");
        }

    }


    @BaseServiceDescribe(moduleName = "补货单", btnName = "确认补货单")
    @Transactional
    public Integer confirmOrder(List<String> idList, String qrry, String hzid) throws SucessException, ServiceException {

        WmsOwner wmsOwner = wmsOwnerMapper.selectById(hzid);//获取货主的信息
        //(1)	只能确认补货单生成状态为“初始”  补货单状态为“已生成”的单子

        //获取选中id的集合
        List<WmsOrderRepair> list = dao.selectBatchIds(idList);
        List<String> list2 = new ArrayList<String>();
        for (WmsOrderRepair wor : list) {
            if (("0".equals(String.valueOf(wor.getZt()))) && (CommonInfo.bhsczt0.getType().equals(String.valueOf(wor.getSczt())))) {
                list2.add(wor.getId());
            }
        }


        if (list2.size() > 0) {
            Integer b = dao.confirmOrder(list2, qrry);//确认补货单，修改确认人和确认时间，状态
            if (b > 0) {
                //确认后根据订单驱动补货明细表中的库存ID，将库存ID对应的库存扣减待补货数量，扣减数量。
                // List<WmsOrderRepairDetailed> detailedList = wmsOrderRepairDetailedMapper.selectList(new EntityWrapper<WmsOrderRepairDetailed>().in("dbhid", list2));
                List<WmsOrderRepairDetailed> detailedList = dao.selectListById(list2);
                Integer c = 0;
                Integer d = 0;
                String msg = "";
                for (WmsOrderRepairDetailed word : detailedList) {
                    //获取拣货位的库存
                    WmsStock wmsStock = dao.getWmsStock(word.getJhkcid(), word.getHpid());
                    WmsStock ws = wmsStockMapper.selectById(word.getKcid());//通过库存id获取库存对象
                    BigDecimal bhsl = new BigDecimal(ws.getBhsl()).subtract(word.getBhsl());
                    BigDecimal sl = new BigDecimal(ws.getSl()).subtract(word.getBhsl());
                    //int a = bhsl.compareTo(BigDecimal.ZERO);
                    ws.setBhsl(String.valueOf(bhsl.intValue()));//原待补货数量减去补货数量
                    ws.setSl(String.valueOf(sl.intValue()));
                    Integer a = wmsStockMapper.updateById(ws);//将库存ID对应的库存扣减待补货数量，扣减数量。

                    //如果库存中存在该货品对应的库存那么直接在库存对应的数量上加上确认的数量，否则新建一条该货品对应拣货位的库存
                    String kcid = "";
                    if (wmsStock == null) {
                        //将补货数量生成新的库存。新库存与原库存只有库位、数量、创建时间的不同，
                        // 新生成的待拣货数量、待补货数量、破损数量、冻结数量全部为零。其他字段与原库存相同。
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                        ws.setCjsj(df.format(new Date()));
                        ws.setSl(String.valueOf(word.getBhsl().intValue()));//数量为补货数量
                        ws.setKwid(word.getJhkcid());//库位
                        ws.setDxjsl("0");
                        ws.setDzysl("0");
                        ws.setDjsl("0");
                        ws.setPssl("0");
                        ws.setId(UUIDUtils.uuid());
                        c = wmsStockMapper.baseInsertSelective(ws);//生成新的库存
                        WmsOrderRepairDetailed wmsOrderRepairDetailed = new WmsOrderRepairDetailed();
                        //修改补货库存记录的确认库存id
                        wmsOrderRepairDetailedMapper.updateQrkc(word.getId(), ws.getId());
                        kcid = ws.getId();
                        c++;
                         //如果货主配置中的 是否对接DPS为1（已对接），那么调用DPS 接口
                         if(wmsOwner.getDjdps().equals("1")){
                             //对接DPS
                             Inventory inventory = new Inventory();
                             inventory.setID(UUIDUtils.uuid());
                             inventory.setCLocation(word.getKwmc());//库位名称
                             inventory.setProNO(word.getHpbh());//货品编号
                             inventory.setUnitName(word.getMs());//散支单位名称
                             inventory.setItemNum(word.getBhsl().intValue());//修改数量
                             inventory.setFlag(1);//增加或者扣减标志（0、扣减库存 1、增加库存）
                             Service1 service1 = new Service1();
                             Result resultInfo = service1.getService1Soap().modifyInventory(inventory);
                             msg = resultInfo.getSMsg();
                             //异常信息插入日志表
                             int count = baseInsertLog(msg, word);
                         }


                    } else {
                        wmsStock.setSl(String.valueOf((word.getBhsl().add(new BigDecimal(wmsStock.getSl()))).intValue()));
                        d = wmsStockMapper.baseUpdateByPrimaryKeySelective(wmsStock);
                        //修改补货库存记录的确认库存id
                        wmsOrderRepairDetailedMapper.updateQrkc(word.getId(), wmsStock.getId());
                        kcid = wmsStock.getId();
                        d++;
                        //如果货主配置中的 是否对接DPS为1（已对接），那么调用DPS 接口
                        if(wmsOwner.getDjdps().equals("1")){
                            //对接DPS
                            Inventory inventory = new Inventory();
                            inventory.setID(UUIDUtils.uuid());
                            inventory.setCLocation(wmsStock.getKwmc());//库位名称
                            inventory.setProNO(wmsStock.getHpbh());//货品编号
                            inventory.setUnitName(wmsStock.getMs());//散支单位名称
                            inventory.setItemNum((word.getBhsl().intValue()));//修改数量
                            inventory.setFlag(1);//增加或者扣减标志（0、扣减库存 1、增加库存）
                            Service1 service1 = new Service1();
                            Result resultInfo = service1.getService1Soap().modifyInventory(inventory);
                            msg = resultInfo.getSMsg();

                            //异常信息插入日志表
                            int count = baseInsertLog(msg, word);
                        }

                    }

                }
                if (msg != null && msg != "") {
                    throw new ServiceException(msg);
                } else {
                    throw new SucessException("补货确认成功");
                }

            } else {
                throw new ServiceException("补货单确认失败");
            }
        } else {
            throw new ServiceException("只能确认状态为\'已生成\'且生成状态为\'初始\'的记录");
        }
    }

    /**
     * 确认补货时，如果DPS没有对应的货品和库位，那么在我们这里增加异常信息
     *
     * @param msg  DPS返回的异常信息
     * @param word 补货明细
     * @return
     */
    public int baseInsertLog(String msg, WmsOrderRepairDetailed word) {
        int a = 0;
        if (msg != "" && !msg.equals("")) {
            WmsReplenishmentLog wmsReplenishmentLog = new WmsReplenishmentLog();
            wmsReplenishmentLog.setId(UUIDUtils.uuid());
            wmsReplenishmentLog.setBhmxid(word.getId());
            wmsReplenishmentLog.setHpbh(word.getHpbh());
            wmsReplenishmentLog.setBhsl(word.getBhsl().intValue());
            wmsReplenishmentLog.setKwmc(word.getKwmc());
            wmsReplenishmentLog.setYcyy(msg);
            a = wmsReplenishmentLogMapper.baseInsert(wmsReplenishmentLog);

        }
        return a;
    }

    /**
     * 导出驱动补货订单
     *
     * @param idList
     * @return
     */
    public List<WmsOrderRepairDetailed> getOutPutList(List<String> idList, Map map) {
        return dao.getOutPutList(idList,map);
    }

    /**
     * 打印补货单
     *
     * @param idList 选中的id
     * @return
     */
    public JSONObject print(List<String> idList) throws ServiceException {

        try {
            WmsOrderRepair wmsOrderRepair = dao.selectByBhid(idList.get(0));
            //List<WmsOrderRepairDetailed> list = dao.getOutPutList(idList);
           // wmsOrderRepair.setWordList(list);
            //dao.getOutPutList(idList)
            return JSONObject.fromObject(wmsOrderRepair);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("打印补货单", e);
        }
    }

    @BaseServiceDescribe(moduleName = "补货单", btnName = "查询明细集合")
    public JSONArray getDetailList(String bhid) throws ServiceException {
        try {
            //发运订单明细
            List<WmsOrderRepairDetailed> list = dao.getDetailList(bhid);
            return JSONArray.fromObject(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询发运订单及明细", e);
        }
    }

    @Transactional
    @BaseServiceDescribe(moduleName = "补货单", btnName = "下发补货任务")
    public void addBhRw(String id, String hzid, String userId, String userName, String ckid) throws ServiceException, SucessException {
        //补货单
        WmsOrderRepair wmsOrderRepair = dao.selectById(id);
        //补货单明细集合
        List<WmsOrderRepairDetailed> list = dao.getList(id);
        //货主
        WmsOwner wmsOwner = wmsOwnerMapper.selectById(hzid);
        Integer num = 0;
        //补货单状态为“已生成”的补货单可以点击“下发补货任务”
        if (wmsOrderRepair.getZt() == 0) {// "已生成""
            for (WmsOrderRepairDetailed wmsOrderRepairDetailed : list) {
                //修改补货单的生成状态 为“已生成”
                int a = dao.updateSczt(1, id);
                //把数据写入pda补货任务表
                WmsPdaReplenishment wmsPdaReplenishment = new WmsPdaReplenishment();
                wmsPdaReplenishment.setId(UUIDUtils.uuid());
                wmsPdaReplenishment.setBhdh(wmsOrderRepair.getBhbh());//补货单号
                wmsPdaReplenishment.setBhlx("0");//补货类型 0：订单驱动 1：人工驱动
                wmsPdaReplenishment.setBhckwid(wmsOrderRepairDetailed.getBhckwid());//补货出库位ID
                wmsPdaReplenishment.setBhckw(wmsOrderRepairDetailed.getBhckw());//补货出库位
                wmsPdaReplenishment.setBhrkwid(wmsOrderRepairDetailed.getBhrkwid());//补货入库位ID
                wmsPdaReplenishment.setBhrkw(wmsOrderRepairDetailed.getBhrkw());//补货入库位
                wmsPdaReplenishment.setHpbh(wmsOrderRepairDetailed.getHpbh());
                wmsPdaReplenishment.setHpmc(wmsOrderRepairDetailed.getHpmc());
                wmsPdaReplenishment.setHpid(wmsOrderRepairDetailed.getHpid());
                wmsPdaReplenishment.setBhsl(wmsOrderRepairDetailed.getBhsl());
                wmsPdaReplenishment.setBhryid(userId);//补货人员id
                wmsPdaReplenishment.setBhrymc(userName);//补货人员名称
                wmsPdaReplenishment.setBhdid(wmsOrderRepair.getId());
                wmsPdaReplenishment.setKcid(wmsOrderRepairDetailed.getKcid());
                //如果货主的扫描货品码和扫描lpn 码为“是”，给lpn码和货品码赋值
                if (wmsOwner.getCmhpm().equals("1") && wmsOwner.getSmLpn().equals("1")) {
                    wmsPdaReplenishment.setLpn(wmsOrderRepairDetailed.getLpn());
                    wmsPdaReplenishment.setHptm(wmsOrderRepairDetailed.getHpbh());//给货品码赋货品编码 的值
                }
                wmsPdaReplenishment.setXdw(wmsOrderRepairDetailed.getXdw());//箱单位描述
                wmsPdaReplenishment.setZdw(wmsOrderRepairDetailed.getZdw());//主单位描述
                wmsPdaReplenishment.setHsl(new BigDecimal(wmsOrderRepairDetailed.getHsl()));//换算量
                wmsPdaReplenishment.setHppc(wmsOrderRepairDetailed.getHppc());
                wmsPdaReplenishment.setScrq(wmsOrderRepairDetailed.getScrq());
                wmsPdaReplenishment.setGys(wmsOrderRepairDetailed.getGys());
                wmsPdaReplenishment.setCkid(ckid);
                wmsPdaReplenishment.setHzid(hzid);
                wmsPdaReplenishment.setGys(wmsOrderRepairDetailed.getGys());
                wmsPdaReplenishment.setBhmxid(wmsOrderRepairDetailed.getId());
                wmsPdaReplenishment.setHppc(wmsOrderRepairDetailed.getHppc());
                wmsPdaReplenishment.setScrq(wmsOrderRepairDetailed.getScrq());
                wmsPdaReplenishment.setSfkjdps(wmsOwner.getDjdps());
                wmsPdaReplenishmentMapper.baseInsertSelective(wmsPdaReplenishment);

                num++;
            }
            //pda消息表
            WmsPdaMsg wmsPdaMsg=new WmsPdaMsg();
            wmsPdaMsg.setRyid(userId);
            wmsPdaMsg.setBt(wmsOrderRepair.getBhbh());
            wmsPdaMsg.setXx(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+" 订单补货下发补货任务");
            wmsPdaMsg.setZt("0");
            wmsPdaMsgMapper.baseInsertSelective(wmsPdaMsg);
            if (num > 0) {
                throw new SucessException("下发补货任务成功");
            } else {
                throw new ServiceException("下发补货任务失败");
            }
        } else {
            throw new ServiceException("只能下发状态为 已生成 的补货单");
        }
    }


    /**
     * 插入一条记录
     *
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsert(WmsOrderRepair entity) {
        return dao.baseInsert(entity);
    }

    /**
     * 插入一条记录（匹配有值的字段）
     *
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsertSelective(WmsOrderRepair entity) {
        return dao.baseInsertSelective(entity);
    }

    /**
     * 删除（根据主键ID删除）
     *
     * @param id 主键
     * @return int
     */
    public Integer baseDeleteByPrimaryKey(String id) {
        return dao.baseDeleteByPrimaryKey(id);
    }

    /**
     * 删除（根据ID 批量删除）
     *
     * @param idList 主键ID列表
     * @return int
     */
    public Integer baseDeleteBathPrimaryKeys(List<String> idList) {
        return dao.baseDeleteBathPrimaryKeys(idList);
    }


    /**
     * 查询（根据主键ID查询）
     *
     * @param id 主键ID
     * @return WmsOrderRepair
     */
    public WmsOrderRepair baseSelectByPrimaryKey(String id) {
        return dao.baseSelectByPrimaryKey(id);
    }

    /**
     * 查询（根据ID 批量查询）
     *
     * @param idList 主键ID列表
     * @return list
     */
    public Integer baseSelectBathPrimaryKeys(List<WmsOrderRepair> idList) {
        return dao.baseSelectBathPrimaryKeys(idList);
    }

    /**
     * 修改 （匹配有值的字段）
     *
     * @param entity 主键ID列表
     * @return int
     */
    public Integer baseUpdateByPrimaryKeySelective(WmsOrderRepair entity) {
        return dao.baseUpdateByPrimaryKeySelective(entity);
    }

    /**
     * 修改（根据主键ID修改）
     *
     * @param entity 主键ID列表
     * @return int
     */
    public Integer baseUpdateByPrimaryKey(WmsOrderRepair entity) {
        return dao.baseUpdateByPrimaryKey(entity);
    }
}
